﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.ConstrainedExecution;
using System.Security.Policy;
using System.Web.Mvc;
using BoneSystem.Extensions.Annotations;
using BoneSystem.Extensions.Annotations.InputTypeAnnotations;
using BoneSystem.Extensions.Form;

namespace BoneSystem.Extensions.Components
{
    public partial class BoneSystemExtensions
    {

        public static InputAttribute BsInputFor<T, TProperty>(this HtmlHelper<T> htmlHelper,
                    Expression<Func<T, TProperty>> expression)
        {
            var name = ExpressionHelper.GetExpressionText(expression);
            var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

            
            var value = ControlHelper.GetValuePropertie(htmlHelper.ViewData.Model, name);
            var inputRet = ControlHelper.GetAnnotations<T, TProperty>(htmlHelper, expression);
            
            if (value == null)
            {
                value = "";
            }
            if (inputRet is FileUploadAttribute)
            {
                inputRet.NgModel = name;
            }
            else
            {
                inputRet.NgModel = name;
            }
            inputRet.Name = name;
            inputRet.Id = name.Replace('.','_') + "_I";
            inputRet.Value = value;
            return inputRet;
        }

        public static void BsInputFor<T, TProperty>(this HtmlHelper<T> htmlHelper,
                    Expression<Func<T, TProperty>> expression, FormLayout<T, TProperty> formLayout)
        {
            var input = BsInputFor(htmlHelper, expression);
            if (formLayout != null)
            {
                formLayout.BsAddInput(input);
            }

        }



        public static MvcHtmlString BsInputFor<T, TProperty>(this HtmlHelper<T> htmlHelper,
                    Expression<Func<T, TProperty>> expression, Settings settings)
        {

            var name = ExpressionHelper.GetExpressionText(expression);
            var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
            var validators = metadata.GetValidators(htmlHelper.ViewContext);
            var enums = validators.GetEnumerator();

            return TextBox(htmlHelper, name, metadata.Model.ToString(), new Dictionary<string, string> { });
        }
    }
}
